<template>
  <div class="app-container">
    <div style="margin: 12px 0;">
      <el-button type="primary" @click="handleInsertSysRole">新增角色</el-button>
    </div>
    <!-- table数据 -->
    <el-table
      :data="sysRoleList"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="appCode" label="应用编码" align="center">
      </el-table-column>
      <el-table-column prop="name" label="角色名称" align="center">
      </el-table-column>
      <el-table-column prop="code" label="角色唯一标识" align="center">
      </el-table-column>
      <el-table-column
        prop="remark"
        label="角色备注"
        align="center"
      >
      </el-table-column>
      <el-table-column label="创建时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.addTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.editTime }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            size="small"
            @click="handleUserSysRoleById(row)"
            style="color: #67C23A"
            >绑定用户</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleGetSysRoleById(row)"
            style="color: green"
            >详情</el-button
          >
          <el-button type="text" size="small" @click="handleEditSysRole(row)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleDelSysRole(row)"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="handleGetSysRoleListsByCode"
    />

    <!-- 新增修改信息 -->
    <el-drawer
      size="40%"
      :close-on-press-escape="false"
      :visible.sync="dialogSysRoleFormVisible"
      :wrapperClosable="false"
      :title="dialogSysRoleFormTitle"
    >
      <el-form ref="sysRoleForm" :model="sysRoleForm" :rules="sysRoleFormRules">
        <el-row>
          <el-col :span="22">
            <el-form-item label="角色名称" label-width="135px" prop="name">
              <el-input
                v-model="sysRoleForm.name"
                autocomplete="off"
                maxlength="100"
                placeholder="请输入角色名称"
                :disabled="!isShowSubmitBtn"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item
              label="角色唯一标识"
              label-width="135px"
              prop="code"
            >
              <el-input
                v-model="sysRoleForm.code"
                autocomplete="off"
                maxlength="100"
                placeholder="请输入角色唯一标识"
                :disabled="!isShowSubmitBtn"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item
              label="应用编码"
              label-width="135px"
              prop="appCode"
            >
              <el-input
                v-model="sysRoleForm.appCode"
                autocomplete="off"
                maxlength="100"
                :disabled="true"
                placeholder="应用编码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item
              label="角色备注"
              label-width="135px"
              prop="remark"
            >
              <el-input
                v-model="sysRoleForm.remark"
                autocomplete="off"
                maxlength="200"
                placeholder="请输入角色备注"
                :disabled="!isShowSubmitBtn"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item
              label="角色具体信息"
              label-width="135px"
              prop="roleExt"
            >
              <vue-json-editor
                v-model="sysRoleForm.roleExt"
                :showBtns="false"
                :mode="'code'"
                lang="zh"
                :expandedOnStart="false"
                @json-change="onJsonSave"
                @json-save="onJsonSave"
                @has-error="onError"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
      <div class="el_drawer_footerbtn">
        <el-button style="margin: 0 10px" @click="handleCloseSysRoleForm"
          >取 消</el-button
        >
        <el-button type="primary" v-if="isShowSubmitBtn" @click="handleSysRoleSubmit('sysRoleForm')"
          >确 定</el-button
        >
      </div>
    </el-drawer>

    <!-- 绑定用户 -->
    <el-drawer
      size="60%"
      :close-on-press-escape="false"
      :visible.sync="dialogSysRoleBindUser"
      :wrapperClosable="false"
      title="绑定用户"
    >
        <el-row style="padding-top:20px;">
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>已绑定用户列表</span>
              </div>
              <div style="max-height: 600px;overflow-y: scroll;">
                <el-table
                :data="bindUserList"
                style="width: 100%" empty-text="暂无数据，请使用右侧表单搜索绑定">
                <el-table-column prop="userName" label="用户名称" align="center">
                </el-table-column>
                <el-table-column prop="loginName" label="登录账号" align="center">
                </el-table-column>
                <el-table-column fixed="right" label="操作" align="center">
                  <template slot-scope="{ row }">
                    <el-button
                      type="text"
                      size="small"
                      style="color: red"
                      @click="handleUnbindUserBySysRoleId(row)"
                      >解绑</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>查找用户</span>
                <el-input
                  size="mini"
                  v-model="listQuery.searchKey"
                  placeholder="请输入用户名称或登录名称搜索"
                  style="width: 250px;"
                  class="filter-item"
                  @keyup.enter.native="handleFilterUserLists"
                  @input="handleFilterUserLists"
                ><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
              </div>
              <div style="max-height: 600px;overflow-y: scroll;">
                
              <el-table
                :data="userInfoLists"
                style="width: 100%" empty-text="请在上方搜索框内输入关键字">
                  <el-table-column prop="userName" label="用户名称" align="center">
                  </el-table-column>
                  <el-table-column prop="loginName" label="登录账号" align="center">
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" align="center">
                    <template slot-scope="{ row }">
                      <el-button
                        type="text"
                        size="small"
                        :disabled="bindUserIdsList.includes(row.id)"
                        @click="handleBindUserToSysRole(row)"
                        >绑定</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-col>
        </el-row>
      <div class="el_drawer_footerbtn" style="margin-top:30px;">
        <el-button style="margin: 0 10px" @click="handleCloseBindUserSysRoleForm"
          >关 闭</el-button
        >
      </div>
    </el-drawer>

  </div>
</template>
  <script>
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
// 导入模块
import vueJsonEditor from "vue-json-editor";
import { getSysRoleListsByCode,insertSysRoleByCode,updateSysRoleByCode,deleteSysRoleById,getSysRoleById, unbindUserIdSysUserRole,bindUserIdSysUserRole,getSysUserRoleList } from "@/api/accredit";
import { mapGetters } from "vuex";
import { setEncryptStrData } from "@/utils/jsencrypt";
import { v4 as uuidv4 } from 'uuid';
import { get } from "js-cookie";
import { getUserListPage } from "@/api/accreditUser";

export default {
  name: "Accredit",
  components: { Pagination, vueJsonEditor },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  computed: {
    ...mapGetters([
      'roles'
    ]),
  },
  data() {
    return {
      appCode: "",
      sysRoleList: [],
      total: 0,
      // 查询参数
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        searchKey: null,
      },
      // 表单检验
      sysRoleFormRules: {
        name: [{ required: true, message: "请填写角色名称", trigger: "blur" }],
        code: [{ required: true, message: "请填写角色唯一标识", trigger: "blur" }],
        appCode: [{ required: true, message: "", trigger: "blur" }],
        remark: [
          { required: true, message: "请填写角色备注", trigger: "blur" },
        ],
        roleExt: [
          { required: true, message: "请填写角色具体信息", trigger: "blur" },
        ],
      },
      dialogSysRoleFormVisible: false,
      dialogSysRoleFormTitle: "",
      sysRoleForm: {
        name:"",
        code:"",
        appCode:"",
        remark:"",
        roleExt:{}
      },
      isShowSubmitBtn: true,
      dialogSysRoleBindUser: false,
      userInfoLists:[],
      bindUserList: [],
      bindUserIdsList: [],
      roleId: null,
    };
  },
  async created() {
    const { appcode } = this.$route.query;
    if (appcode) {
      this.sysRoleForm.appCode = appcode;
      this.appCode = appcode;
      this.handleGetSysRoleListsByCode();
    }else{
      this.$message({
        message: "缺失项目编码",
        type: "error",
      });
      this.$router.push({ path: "/accredit/index" });
    }
    
  },
  methods: {
    //  请求头准备
    async dealAjaxHeaders() {
      const _uid = uuidv4();
      const _loginEncrypt = await setEncryptStrData(_uid);
      return await this.$store.dispatch("user/setMfAgent", {uuid:_uid, agentId:_loginEncrypt});
    },
    //  角色列表查询
    async handleGetSysRoleListsByCode(){
      await this.dealAjaxHeaders();
      const lists = await getSysRoleListsByCode({appCode:this.appCode},this.listQuery.pageNum,this.listQuery.pageSize);
      if(lists.success && lists.data.totalSize){
        this.total = lists.data.totalSize;
        this.sysRoleList = lists.data.data || [];
      }else{
        this.total = 0;
        this.sysRoleList = [];
      }
    },
    //  新增角色
    async handleInsertSysRole(){
      this.isShowSubmitBtn = true;
      this.dialogSysRoleFormTitle = "新增角色";
      this.dialogSysRoleFormVisible = true;
    },
    //  编辑角色
    async handleEditSysRole(row){
      this.isShowSubmitBtn = true;
      this.sysRoleForm ={
        id: row.id,
        name: row.name,
        code: row.code,
        appCode: row.appCode,
        remark: row.remark,
        roleExt: row.roleExt ? JSON.parse(row.roleExt) : {}
      }
      this.dialogSysRoleFormVisible = true;
      this.dialogSysRoleFormTitle = "编辑角色";
    },
    // 删除角色
    async handleDelSysRole(row){
      this.$confirm("是否删除当前选中的角色信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteSysRoleById(row.id)
          if(res.success){
            this.handleGetSysRoleListsByCode();
            this.$message({
              message: "删除成功",
              type: "success",
            });
          }else{
            this.$message({
              message: "删除失败",
              type: "error",
            });
          }
        })
        .catch(() => {});
    },
    // 查询角色详情
    async handleGetSysRoleById(row){
      this.isShowSubmitBtn = false;
      this.dialogSysRoleFormVisible = true;
      this.dialogSysRoleFormTitle = "查看角色详情";
      const res = await getSysRoleById(row.id);
      if(res.success && res.data){
        this.sysRoleForm ={
          id: res.data.id,
          name: res.data.name,
          code: res.data.code,
          appCode: res.data.appCode,
          remark: res.data.remark,
          roleExt: res.data.roleExt ? JSON.parse(res.data.roleExt) : {}
        }
      }else{
        this.$message({
          message: "查询失败",
          type: "error",
        });
      }
    },
    //  关闭角色弹窗
    async handleCloseSysRoleForm(){
      this.dialogSysRoleFormVisible = false;
      this.dialogSysRoleFormTitle = "";
      this.sysRoleForm ={
        name:"",
        code:"",
        appCode: this.appCode,
        remark:"",
        roleExt:{}
      }
    },
    //  角色更新和提交
    handleSysRoleSubmit(formName){
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.dealAjaxHeaders();
          if (this.sysRoleForm.id) {
            const updateRes = await updateSysRoleByCode({
              id: this.sysRoleForm.id,
              name: this.sysRoleForm.name,
              code: this.sysRoleForm.code,
              appCode: this.sysRoleForm.appCode,
              remark: this.sysRoleForm.remark,
              roleExt: JSON.stringify(this.sysRoleForm.roleExt)
            });
            if(updateRes.success){
              this.handleCloseSysRoleForm();
              this.handleGetSysRoleListsByCode();
              this.$message({
                message: "编辑成功",
                type: "success",
              });
            }else{
              this.$message({
                message: "编辑失败",
                type: "error",
              });
            }
          } else {
            const insertRes = await insertSysRoleByCode({
              name: this.sysRoleForm.name,
              code: this.sysRoleForm.code,
              appCode: this.sysRoleForm.appCode,
              remark: this.sysRoleForm.remark,
              roleExt: JSON.stringify(this.sysRoleForm.roleExt)
            });
            if(insertRes.success){
              this.handleCloseSysRoleForm();
              this.handleGetSysRoleListsByCode();
              this.$message({
                message: "新增成功",
                type: "success",
              });
            }else{
              this.$message({
                message: "新增失败",
                type: "error",
              });
            }
          }
        }
      });
    },
    //  根据角色id查询用户列表
    async getBindUserListsByRoleId(){
      const res = await getSysUserRoleList(this.roleId);
      this.bindUserList = res.success ? res.data : [];
      let _arr = [];
      for(let i = 0; i < this.bindUserList.length; i++){
        _arr.push(this.bindUserList[i].id)
      }
      this.bindUserIdsList = _arr;
    },
    //  角色绑定用户信息
    async handleUserSysRoleById(row){
      this.roleId = row.id;
      await this.dealAjaxHeaders();
      //  查询当前角色绑定的用户信息
      this.getBindUserListsByRoleId();
      this.dialogSysRoleBindUser = true;
    },
    //  关闭绑定弹窗
    async handleCloseBindUserSysRoleForm(){
      this.dialogSysRoleBindUser = false;
      this.roleId = null;
      this.bindUserList = [];
      this.bindUserIdsList = [];
    },
    //  列表查询
    async handleFilterUserLists(){
      try{
        this.userInfoLists = [];
        if(!this.listQuery.searchKey) return;
        const _listsRes = await getUserListPage({
          "userName": this.listQuery.searchKey,
          "loginName": this.listQuery.searchKey,
        },this.listQuery.pageNum, this.listQuery.pageSize);
        if(_listsRes.success && _listsRes.data && _listsRes.data.totalSize){
          this.userInfoLists = _listsRes.data.data;
        }
      }catch(e){
        this.$message({
          type: 'error',
          message: '用户信息查询失败'
        })
      }
    },
    //  绑定用户信息至角色
    async handleBindUserToSysRole(row){
      await this.dealAjaxHeaders();
      let bindData = [];
      //  组装已绑定的用户数据
      for(let i = 0; i < this.bindUserList.length; i++){
        bindData.push({
          userId: this.bindUserList[i].id,
          roleId: this.roleId
        })
      }
      bindData.push({ userId: row.id, roleId: this.roleId });

      const res = await bindUserIdSysUserRole(bindData, this.roleId);
      if(res.success){
        this.$message({
          type: 'success',
          message: '绑定成功'
        })
        this.getBindUserListsByRoleId();
      }else{
        this.$message({
          type: 'error',
          message: '绑定失败'
        })
      }
    },
    //  解绑用户信息
    async handleUnbindUserBySysRoleId(row){
      this.$confirm("是否将当前用户从该角色中移除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.dealAjaxHeaders();
          const res = await unbindUserIdSysUserRole(row.id, this.roleId)
          if(res.success){
            this.getBindUserListsByRoleId();
            this.$message({
              message: "解绑成功",
              type: "success",
            });
          }else{
            this.$message({
              message: "解绑失败",
              type: "error",
            });
          }
        })
        .catch(() => {});
    },
    // json编辑器回调方法
		onJsonSave(value) {
			this.sysRoleForm.roleExt = value;
		},
		onError(value) {
		},
  },
};
</script>
    
    <style lang="scss">
.filter-containers {
  display: flex;
  justify-content: space-between;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.bind_box{
  padding: 30px 12px;
}
.clearfix{
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
      